#!/bin/bash

#############################################
# 构建并推送 netdisk-svc Docker 镜像
# 默认推送到 192.168.0.104:5000/library/netdisk-svc:1.0.0
#############################################

set -euo pipefail

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'

# 项目根目录
PROJECT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"

# 默认参数（可通过环境变量覆盖）
REGISTRY_HOST="${REGISTRY_HOST:-192.168.0.104:5000}"
IMAGE_NAME="${IMAGE_NAME:-library/netdisk-svc}"
IMAGE_TAG="${IMAGE_TAG:-1.0.0}"
DOCKERFILE_PATH="${DOCKERFILE_PATH:-${PROJECT_ROOT}/Dockerfile}"

# 完整镜像名
FULL_IMAGE="${REGISTRY_HOST}/${IMAGE_NAME}:${IMAGE_TAG}"

print_usage() {
  cat <<EOF
用法:
  ./script/build_and_push.sh [--registry host:port] [--image repo/name] [--tag tag] [--dockerfile path]

示例:
  ./script/build_and_push.sh
  ./script/build_and_push.sh --registry 192.168.0.104:5000 --image library/netdisk-svc --tag 1.0.1
  ./script/build_and_push.sh --dockerfile ./db/init/Dockerfile --image library/netdisk-db-init --tag 1.0.0

环境变量覆盖:
  REGISTRY_HOST   默认: 192.168.0.104:5000
  IMAGE_NAME      默认: library/netdisk-svc
  IMAGE_TAG       默认: 1.0.0
  DOCKERFILE_PATH 默认: 项目根目录下的 Dockerfile
EOF
}

while [[ $# -gt 0 ]]; do
  case "$1" in
    --registry)
      REGISTRY_HOST="$2"; shift 2 ;;
    --image)
      IMAGE_NAME="$2"; shift 2 ;;
    --tag)
      IMAGE_TAG="$2"; shift 2 ;;
    --dockerfile)
      DOCKERFILE_PATH="$2"; shift 2 ;;
    -h|--help)
      print_usage; exit 0 ;;
    *)
      echo -e "${RED}未知参数: $1${NC}" >&2
      print_usage
      exit 1 ;;
  esac
done

FULL_IMAGE="${REGISTRY_HOST}/${IMAGE_NAME}:${IMAGE_TAG}"

echo -e "${GREEN}================================${NC}"
echo -e "${GREEN}构建并推送 Docker 镜像${NC}"
echo -e "${GREEN}================================${NC}"
echo -e "项目目录:   ${YELLOW}${PROJECT_ROOT}${NC}"
echo -e "Dockerfile: ${YELLOW}${DOCKERFILE_PATH}${NC}"
echo -e "目标镜像:   ${YELLOW}${FULL_IMAGE}${NC}"
echo -e "${GREEN}================================${NC}"

# 前置检查
if ! command -v docker >/dev/null 2>&1; then
  echo -e "${RED}错误: 未找到 docker，请先安装 Docker 环境${NC}" >&2
  exit 1
fi

if [[ ! -f "${DOCKERFILE_PATH}" ]]; then
  echo -e "${RED}错误: Dockerfile 不存在: ${DOCKERFILE_PATH}${NC}" >&2
  exit 1
fi

echo -e "${YELLOW}步骤 1/3: 构建镜像...${NC}"
docker build -t "${FULL_IMAGE}" -f "${DOCKERFILE_PATH}" "${PROJECT_ROOT}"

echo -e "${YELLOW}步骤 2/3: 推送镜像...${NC}"
echo -e "${YELLOW}如果尚未登录，请执行: docker login ${REGISTRY_HOST}${NC}"
docker push "${FULL_IMAGE}"

echo -e "${YELLOW}步骤 3/3: 查看镜像信息...${NC}"
docker image inspect "${FULL_IMAGE}" >/dev/null && {
  SIZE=$(docker image inspect "${FULL_IMAGE}" --format='{{.Size}}')
  CREATED=$(docker image inspect "${FULL_IMAGE}" --format='{{.Created}}')
  echo -e "${GREEN}镜像大小: ${SIZE} bytes${NC}"
  echo -e "${GREEN}创建时间: ${CREATED}${NC}"
}

echo -e "${GREEN}✓ 操作完成${NC}"
echo
echo -e "后续步骤建议:"
echo -e "  1. 在目标环境上运行: docker pull ${FULL_IMAGE}"
echo -e "  2. 更新 k8s Deployment 使用新镜像标签"
echo -e "  3. 重新部署服务以加载新镜像"

